package com.w2a.template;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

//依赖：implementation 'com.squareup.okhttp3:okhttp:4.12.0' //最稳定版本
public class HttpHelper {
    private static final OkHttpClient client = new OkHttpClient();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    public static String token = null;

    public interface Callback {
        void onRes(boolean success, String response);
    }

    public static void getAsync(String url, Callback callback) {
        Request.Builder builder = new Request.Builder().url(url);
        if (token != null && !token.isEmpty()) {
            builder.addHeader("Authorization", "Bearer " + token);
        }
        Request request = builder.get().build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                error("Get请求失败[" + url + "]：" + e);
                mainHandler.post(() -> {
                    if (callback != null) callback.onRes(false, e.toString());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    boolean suc;
                    if (!response.isSuccessful()) {
                        error("Get响应失败[" + url + "]：" + response);
                        suc = false;
                    } else {
                        suc = true;
                    }
                    ResponseBody body = response.body();
                    String res = body != null ? body.string() : "";
                    mainHandler.post(() -> {
                        if (callback != null) callback.onRes(suc, res);
                    });
                } catch (IOException e) {
                    error("Get响应报错[" + url + "]：" + e);
                    mainHandler.post(() -> {
                        if (callback != null) callback.onRes(false, e.toString());
                    });
                }
            }
        });
    }

    public static void postAsync(String url, JSONObject data, Callback callback) {
        RequestBody body = RequestBody.create(data.toString(), MediaType.parse("application/json; charset=utf-8"));
        Request.Builder builder = new Request.Builder().url(url);
        if (token != null && !token.isEmpty()) {
            builder.addHeader("Authorization", "Bearer " + token);
        }
        Request request = builder.post(body).build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                error("Post请求失败[" + url + "]：" + e);
                mainHandler.post(() -> {
                    if (callback != null) callback.onRes(false, e.toString());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    boolean suc;
                    if (!response.isSuccessful()) {
                        error("Post响应失败[" + url + "]：" + response);
                        suc = false;
                    } else {
                        suc = true;
                    }
                    ResponseBody body = response.body();
                    String res = body != null ? body.string() : "";
                    mainHandler.post(() -> {
                        if (callback != null) callback.onRes(suc, res);
                    });
                } catch (IOException e) {
                    error("Post响应报错[" + url + "]：" + e);
                    mainHandler.post(() -> {
                        if (callback != null) callback.onRes(false, e.toString());
                    });
                }
            }
        });
    }

    private static void log(String msg) {
        Log.i("[B]" + HttpHelper.class.getSimpleName(), msg);
    }

    private static void error(String msg) {
        Log.e("[B]" + HttpHelper.class.getSimpleName(), msg);
    }
}